<!DOCTYPE html>
<html lang="zh">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport"
			content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title style="font-size: 20px;">安全区域设置</title>

		<style type="text/css">
			html {
				height: 100%
			}

			body {
				height: 100%;
				margin: 0px;
				padding: 0px;
				overflow: hidden;
			}

			#map {
				width: 100%;
				height: 100%;
			}

			.btns {
				display: flex;
				flex-direction: column;
				z-index: 9999;
				position: absolute;
				bottom: 5%;
				right: 0%;
				width: 80px;
				overflow: hidden;
				align-items: center;
			}

			button {
				width: 50px;
				height: 50px;
				border-radius: 50%;
				outline: none;
				border: none;
				margin-bottom: 10px;
				background-color: #f1f1f1;
				color: #fff;
				z-index: 99999;

			}

			#localtion {
				background-image: url("map/a-dingwei2.png");
				background-size: 50%;
				background-repeat: no-repeat;
				/* 防止背景图片重复 */
				background-position: 50%;

			}

			.gm-style iframe+div {
				border: none !important;
			}

			a[href^="http://maps.google.com/maps"] {
				display: none !important
			}

			a[href^="https://maps.google.com/maps"] {
				display: none !important
			}

			.gmnoprint a,
			.gmnoprint span,
			.gm-style-cc {
				display: none;
			}

			.gmnoprint div {
				background: none !important;
			}
		</style>
	</head>

	<body>
		<div id='map'></div>
		<div class="btns">
			<button id="localtion"> </button>
		</div>
	</body>

	<script type="text/javascript" src="../uni.webview.1.5.2.js">
	</script>
	<script>
		(g => {
			var h, a, k, p = "The Google Maps JavaScript API",
				c = "google",
				l = "importLibrary",
				q = "__ib__",
				m = document,
				b = window;
			b = b[c] || (b[c] = {});
			var d = b.maps || (b.maps = {}),
				r = new Set,
				e = new URLSearchParams,
				u = () => h || (h = new Promise(async (f, n) => {
					await (a = m.createElement("script"));
					e.set("libraries", [...r] + "");
					for (k in g) e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]);
					e.set("callback", c + ".maps." + q);
					a.src = `https://maps.${c}apis.com/maps/api/js?` + e;
					d[q] = f;
					a.onerror = () => h = n(Error(p + " could not load."));
					a.nonce = m.querySelector("script[nonce]")?.nonce || "";
					m.head.append(a)
				}));
			d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[
				l](f, ...n))
		})({
			key: "AIzaSyCaJJDLbPygLYHFL1vi6AlcQmR1P1rRDvA",
			v: "weekly",
			// Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
			// Add other bootstrap parameters as needed, using camel case.
		});
	</script>
	<script type="text/javascript">
		// 获取url参数
		function getUrlParams(url) {
			const paramsRegex = /[?&]+([^=&]+)=([^&]*)/gi;
			const params = {};
			let match;
			while (match = paramsRegex.exec(url)) {
				params[match[1]] = match[2];
			}
			return params;
		}

		var map;
		var city;
		var marker;
		var cityCircle;
		var centerPostion;
		var cityCircle;
		var addressName;
		var addressPosition;
		// 加载地图
		async function initMap() {
			const {
				Map
			} = await google.maps.importLibrary("maps");

			map = new Map(document.getElementById("map"), {
				zoom: 14,
				mapId: '9acf2d6299ded60c',//"4504f8b37365c3d0"
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				// mapTypeId: google.maps.MapTypeId.TERRAIN,
				zoomControl: false,
				mapTypeControl: false,
				fullscreenControl: false,
				scaleControl: false,
				streetViewControl: false,
				clickableIcons: false,
			});
			
			const {
				AdvancedMarkerElement
			} = await google.maps.importLibrary("marker");
			
			
			const playFlagImg = document.createElement("img");
			playFlagImg.style.width = '40px'
			playFlagImg.style.height = '40px'
			playFlagImg.src = 'map/starter_tracker.png'
			marker = new google.maps.marker.AdvancedMarkerElement({
				map,
				// content: playFlagImg,
			});
			

			// marker = new google.maps.Marker({
			// 	map: map,
			// 	title: 'Click to zoom'
			// });

			cityCircle = new google.maps.Circle({
				strokeColor: "#FF0000",
				strokeOpacity: 0.8,
				strokeWeight: 1,
				fillColor: "#FF0000",
				fillOpacity: 0.35,
				map,
				radius: Math.sqrt(1) * 1,
			});

			// 当地图的中心改变时，更新标记的位置
			google.maps.event.addListener(map, 'center_changed', function() {
				marker.position = map.getCenter();
				cityCircle.setCenter(map.getCenter());
				addressPosition = map.getCenter();
				getAddressName(map.getCenter());
			});

			// 添加标记的点击事件，用于缩放地图
			google.maps.event.addListener(marker, 'click', function() {
				map.setZoom(map.getZoom() + 1);
				// 将地图的中心设置回标记的当前位置
				map.setCenter(marker.getPosition());
			});
			google.maps.event.addListener(cityCircle, 'center_changed', function() {

			});

		}

		//获取当前手机位置
		async function getPhonePostion() {

			//获取当前时间 


			const {
				AdvancedMarkerElement
			} = await google.maps.importLibrary("marker");

			if (navigator.geolocation) {

				navigator.geolocation.getCurrentPosition(function(position) {
					console.log('position', position);
					centerPostion = {
						lat: position.coords.latitude,
						lng: position.coords.longitude
					};
					errormeter = position.coords.accuracy;
					getAddressName();
					setCurrentPostionToCenter(centerPostion);
				}, function() {
					handleLocationError(true, map.getCenter());
				}, { enableHighAccuracy: true });
			} else {
				// 浏览器不支持地理定位
				handleLocationError(false, map.getCenter());
			}
		}

		// 处理地理定位错误
		function handleLocationError(browserHasGeolocation, infoWindow, pos) {
			infoWindow.setPosition(pos);
			infoWindow.setContent(browserHasGeolocation ?
				'Error: The Geolocation service failed.' :
				'Error: Your browser doesn\'t support geolocation.');
		}


		function getAddressName(postion) {
			var geocoder = new google.maps.Geocoder();
			geocoder.geocode({
				'location': postion
			}, function(results, status) {
				if (status === google.maps.GeocoderStatus.OK) {
					// console.log("地名=",JSON.stringify(results));
					if (results[0]) {
						currentAddress = results[0].formatted_address;
						let arr = currentAddress.split(" ");
						addressName = arr[0];
						let data = {
							type: 'address',
							content: {
								addressName: addressName,
								addressPosition: addressPosition,
							}
						}
						uni.postMessage({
							data: data
						})
					} else {
						console.log('No results found');
					}
				} else {
					console.log('Geocoder failed due to: ' + status);
				}
			});
		}


		async function setCurrentPostionToCenter(center) {
			map.setCenter(center);
			marker.setPosition(center);
			cityCircle.setCenter(center);
		}

		function makeFenceCircle(radius) {
			cityCircle.setRadius(radius);

		}

		window.addEventListener('UniAppJSBridgeReady', function() {
			initMap();
			//接收处理app 发来的消息
			window.getVueMessage = (data) => {
				console.log('app发来的消息:', JSON.stringify(data));
				if (data.type == 1) {
					makeFenceCircle(data.radius)
				} else if (data.type == 2) {
					centerPostion = data.content.position;
					console.log(centerPostion.lat,centerPostion.lng);
					makeFenceCircle(data.content.radius);
					setCurrentPostionToCenter(centerPostion);
				}else if (data.type == 3){
					getPhonePostion();
				}
			};

			document.getElementById("localtion").onclick = function() {
				getPhonePostion();
			};
		});

		document.addEventListener('gesturestart', function(event) {
			event.preventDefault()
		})
	</script>